package com.xjoyt.pay.master.core.order.handle.create;

import java.util.Map;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.gateway.params.OrderCreateParam;
import com.xjoyt.pay.gateway.params.OrderParam;
import com.xjoyt.pay.master.core.order.handle.AbstractOrderCreateHandle;
import com.xjoyt.pay.master.dto.OrderUrlResult;
import com.xjoyt.pay.master.params.OrderAdapterParam;
import com.xjoyt.pay.master.po.MerchantChannel;
import com.xjoyt.pay.master.po.Order;
import com.xjoyt.pay.master.po.PayChannel;
import com.xjoyt.pay.vo.PayType;

/**
 * 下单
 * 
 * @author Administrator
 *
 */
@Component
@Scope("prototype")
public class CreateScannedCodeHandle extends AbstractOrderCreateHandle {

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public ExecuteResult<OrderUrlResult> handle(OrderParam param, PayType payType, Map<String, Object> args) {
		Order entity = getObject(Order.class, args);
		PayChannel payChannel = getObject(PayChannel.class, args);
		MerchantChannel merchantChannel = getObject(MerchantChannel.class, args);
		try {
			// 调用适配器支付
			OrderAdapterParam adapterParam = new OrderAdapterParam();
			adapterParam.param = param;
			adapterParam.order = entity;
			adapterParam.payChannel = payChannel;
			adapterParam.merchantChannel = merchantChannel;
			OrderUrlResult result = restTemplate.postForObject(entity.orderConfig.url, adapterParam,
					OrderUrlResult.class);
			entity.success = result.success;
			if (BooleanUtils.isTrue(result.success)) {
				if (StringUtils.isNotBlank(result.tradeNo)) {
					entity.tradeNo = result.tradeNo;
				}
				result.outTradeNo = entity.outTradeNo;
				result.money = entity.money;
				result.no = entity.no;
				repository.save(entity);
				return ExecuteResult.ok(result);
			}
			if (StringUtils.isNotBlank(result.resultMessage)) {
				entity.orderConfig.resultMessage = StringUtils.substring(result.resultMessage, 0, 255);
			}
			entity.orderConfig.resultCode = result.resultCode;
			repository.save(entity);
			return ExecuteResult.fail("下单失败");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("下单服务器异常", e);
			entity.success = false;
			entity.orderConfig.resultMessage = StringUtils.substring(e.getMessage(), 0, 255);
			repository.save(entity);
			return ExecuteResult.fail("下单异常");
		}
	}

}
